package routers

import (
	"fmt"
	"io"
	"net/http"

	"os"

	"github.com/labstack/echo"
)

type UploadFileInfo struct {
	Link string `json:"link"`
}

//@router post /upload/uploadfile
func UploadFile(c echo.Context) error {
	var resp ResponseData
	defer JsonWrite(c, &resp)
	resp.Code = RECODE_OK

	h, err := c.FormFile("file")
	if err != nil {
		fmt.Println("Failed to FormFile", err)
		resp.Code = RECODE_PARAMERR
		return err
	}
	src, err := h.Open()
	defer src.Close()
	dstname := "upload/files/" + h.Filename
	dst, err := os.Create(dstname)
	if err != nil {
		fmt.Println("Failed to Create", err)
		resp.Code = RECODE_PARAMERR
		return err
	}

	resp.Data = UploadFileInfo{dstname}
	_, err = io.Copy(dst, src)
	return err
}

type ResponseUploadFile struct {
	Code  string      `json:"code"`
	Msg   string      `json:"msg"`
	Errno int         `json:"errno"`
	Count string      `json:"count"`
	Data  interface{} `json:"data"`
}

func JsonWriteUpload(c echo.Context, r *ResponseUploadFile) error {
	r.Msg = RecodeText(r.Code)
	return c.JSON(http.StatusOK, r)
}

//@router post /upload/uploadfile
func UploadEditorFiles(c echo.Context) error {
	var resp ResponseUploadFile
	defer JsonWriteUpload(c, &resp)
	resp.Code = RECODE_OK
	resp.Errno = 0
	h, err := c.FormFile("files")
	if err != nil {
		fmt.Println("Failed to FormFile", err)
		resp.Code = RECODE_PARAMERR
		resp.Errno = -1
		return err
	}
	src, err := h.Open()
	defer src.Close()
	dstname := "upload/files/" + h.Filename
	dst, err := os.Create(dstname)
	if err != nil {
		fmt.Println("Failed to Create", err)
		resp.Code = RECODE_PARAMERR
		resp.Errno = -1
		return err
	}

	_, err = io.Copy(dst, src)

	resp.Data = []string{"/" + dstname}

	return err
}
